﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Customer.Infrstructre
{
    public class BaseRepository<T> : IRepository<T> where T : class, new()
    {
        protected readonly EFCoreDBcontext dbContext;

        public BaseRepository(EFCoreDBcontext _dbContext)
        {
            dbContext = _dbContext;
        }

        //添加
        public async Task<int> AddAsync(T entity)
        {
            await dbContext.AddAsync(entity);
            return await dbContext.SaveChangesAsync();
        }
        //删除
        public async Task<int> DelAsync(T entity)
        {
            dbContext.Remove(entity);
            return await dbContext.SaveChangesAsync();
        }
        //显示
        public async Task<List<T>> GetAllAsync()
        {
            return await dbContext.Set<T>().ToListAsync();
        }
        //带有条件的查询
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expr)
        {
            return await dbContext.Set<T>().Where(expr).ToListAsync();
        }
        //反填
        public async Task<T> GetModelAsync(int id)
        {
            return await dbContext.Set<T>().FindAsync(id);
        }
        //修改
        public async Task<int> Update(T entity)
        {
            dbContext.Update(entity);
            return await dbContext.SaveChangesAsync();
        }
    }
}
